<template>
  <a-drawer
    :title="title"
    :closable="false"
    :maskClosable="false"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item label="所属学院" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback forceRender="true">
              <a-select
                show-search
                allowClear
                placeholder="请选择所属学院"
                v-decorator="['collId', { rules: [{ required: true, message: '请选择所属学院！' }] }]"
                :disabled="collSwitch"
              >
                <a-select-option v-for="item of this.collList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item label="实验课程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入实验课程名称"
                v-decorator="['name', { rules: [{ required: true, message: '请输入实验课程名称！' }] }]"
                :disabled="id != ''"
              />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item label="排序号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input-number
                placeholder="请输入排序号"
                v-decorator="['sortNum', { rules: [{ required: true, message: '请输入排序号！' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item
              label="选课限制"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-table
                size="middle"
                :columns="limitColumns"
                :dataSource="limitData"
                :pagination="false"
                :loading="limitLoading"
              >
                <template v-for="(col,index) in ['tagId','reqNum']" :slot="col" slot-scope="text, record">
                  <template v-if="index == 0">
                    <a-select
                      :key="col"
                      style="width: 100%"
                      placeholder="请选择附属职位"
                      :defaultValue="record.tagId"
                      @change="e => handleChange(e,record.key,col)"
                      has-feedback
                    >
                      // eslint-disable-next-line vue/no-template-shadow
                      <a-select-option v-for="(item,indexs) in stuTagList" :key="indexs" :value="item.id">{{ item.name
                        }}
                      </a-select-option>
                    </a-select>
                  </template>
                  <template v-if="index == 1">
                    <a-input-number
                      :key="col"
                      style="width: 100%"
                      placeholder="请输入必选实验数"
                      :value="record.reqNum"
                      @change="e => handleChange(e,record.key,col)"
                      :min="1" :max="10"
                      has-feedback
                    />
                  </template>
                </template>
                <template slot="operation" slot-scope="text, record">
                  <a @click="removeLimit(record.key)">删除</a>
                </template>
              </a-table>
              <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus"
                        @click="newLimit">增行
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <div class="drawer-footer">
      <a-button class="left" @click="handleCancel"> 关闭</a-button>
      <a-button class="right" type="primary" @click="handleSubmit"> 提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
  import { sysCollegeList } from '@/api/modular/system/sysCollegeManage'
  import store from '@/store'
  import { courseAdd, courseDetail, courseEdit } from '@/api/modular/system/courseManage'
  import { tStudentTagList } from '@/api/modular/system/studentTagManage'

  export const dateFormat = 'YYYY-MM-DD'
  export default {
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        id: '',
        title: '',
        collList: [],
        collSwitch: false,
        stuTagList: [],
        limitLoading: false,
        limitData: [],
        limitColumns: [
          {
            title: '学生标签',
            dataIndex: 'tagId',
            width: '45%',
            scopedSlots: { customRender: 'tagId' }
          },
          {
            title: '课程必选实验数',
            dataIndex: 'reqNum',
            width: '45%',
            scopedSlots: { customRender: 'reqNum' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ]
      }
    },
    created() {

    },
    methods: {
      getCollList() {
        sysCollegeList().then((res) => {
          if (res.success) {
            this.collList = res.data
          }
        })
      },
      getStuTagList() {
        tStudentTagList().then((res) => {
          if (res.success) {
            this.stuTagList = res.data
            this.stuTagList.unshift({
              id: '0',
              name: '所有人'
            })
          }
        })
      },
      // 初始化方法
      open(record) {
        this.getCollList()
        this.getStuTagList()
        if (record) {
          this.id = record.id
          this.title = '编辑实验课程信息'
          this.collSwitch = true
          setTimeout(() => {
            this.limitLoading = true
            courseDetail({
              id: record.id
            }).then((res) => {
                if (res.success) {
                  this.form.setFieldsValue({
                    id: res.data.id,
                    sortNum: res.data.sortNum,
                    name: res.data.name,
                    collId: res.data.collId
                  })
                  res.data.limitList.map((item,index)=>{
                    this.limitData.push({
                      key: index,
                      tagId: item.tagId,
                      reqNum: item.reqNum
                    })
                  })
                }
              }
            ).finally(() => {
              this.limitLoading = false
            })
          }, 100)
        } else {
          this.id = ''
          this.title = '新增实验课程信息'
          if (store.getters.admintype != '1') {
            this.collSwitch = true
            setTimeout(() => {
              this.form.setFieldsValue({
                collId: store.getters.userInfo.collId
              })
            }, 100)
          } else {
            this.collSwitch = false
          }
        }
        this.visible = true
      },
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            console.log(values)
            const data = { ...values }
            data.limitList = this.limitData
            if (this.id) {
              data.id = this.id
              courseEdit(data)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('更新实验课程信息成功')
                    this.confirmLoading = false
                    this.$emit('ok', data)
                    this.handleCancel()
                  } else {
                    this.$message.error('更新系实验课程信息失败：' + res.message)
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            } else {
              courseAdd(data)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('新增实验课程信息成功')
                    this.confirmLoading = false
                    this.$emit('ok', data)
                    this.handleCancel()
                  } else {
                    this.$message.error('新增实验课程信息失败：' + res.message)
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel() {
        this.limitLoading = false
        this.limitData = []
        this.form.resetFields()
        this.visible = false
      },
      /**
       * 删除
       */
      removeLimit(key) {
        const newData = this.limitData.filter(item => item.key !== key)
        this.limitData = newData
      },
      /**
       * 增行
       */
      newLimit() {
        const length = this.limitData.length
        this.limitData.push({
          key: length === 0 ? '1' : (parseInt(this.limitData[length - 1].key) + 1).toString(),
          tagId: '',
          reqNum: undefined
        })
      },
      /**
       * 选择子表单单项触发
       */
      handleChange(value, key, column) {
        const newData = [...this.limitData]
        const target = newData.find(item => key === item.key)
        if (target) {
          target[column] = value
          this.limitData = newData
        }
      }
    }
  }
</script>
